﻿using System;

namespace Crypt.Common
{
    public class Aes
    {

        /// 获取Aes32位密钥
        /// </summary>
        /// <param name="key">Aes密钥字符串</param>
        /// <returns>Aes32位密钥</returns>
        private static byte[] CheckAesKey(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key", "Aes密钥不能为空");
            }
            if (key.Length < 32)
            {
                // 不足32补全
                key = key.PadRight(32, '0');
            }
            if (key.Length > 32)
            {
                key = key.Substring(0, 32);
            }
            return System.Text.Encoding.UTF8.GetBytes(key);
        }

        ///<summary>
        ///加密
        ///</summary>
        ///<param name="toEncrypt">需要被加密的数据</param>
        ///<param name="inKey">加密秘钥</param>
        ///<returns></returns>
        public static byte[] Encrypt(byte[] toEncrypt, string inKey)
        {
            Byte[] keyArray = CheckAesKey(inKey);

            System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged();
            aes.Key = keyArray;
            aes.Mode = System.Security.Cryptography.CipherMode.ECB;
            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            System.Security.Cryptography.ICryptoTransform transform = aes.CreateEncryptor();
            Byte[] resultArray = transform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);

            return resultArray;
        }

        ///<summary>
        ///解密
        ///</summary>
        ///<param name="toDecrypt">需要被解密的数据</param>
        ///<param name="inKey">加密秘钥</param>
        ///<returns></returns>
        public static byte[] Decrypt(byte[] toDecrypt, string inKey)
        {
            Byte[] keyArray = CheckAesKey(inKey);

            System.Security.Cryptography.RijndaelManaged aes = new System.Security.Cryptography.RijndaelManaged();
            aes.Key = keyArray;
            aes.Mode = System.Security.Cryptography.CipherMode.ECB;
            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            System.Security.Cryptography.ICryptoTransform transform = aes.CreateDecryptor();
            Byte[] resultArray = transform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);

            return resultArray;
        }
    }
}
